package com.gdkj.util;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
import java.util.Base64;

/**
 * AES加解密工具类
 */
@Slf4j
public class AESUtils {
    // 加密key
    private final static String encryptKey = "gtD@s6Fh7pNU0WWP";
    // 加密偏移量
    private final static String ivByte = "abcdefghijklmnop";

    /**
     * @param originalContent 加密内容
     * @return
     */
    public static String encrypt(String originalContent) {
        Security.addProvider(new BouncyCastleProvider());
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec skeySpec = new SecretKeySpec(encryptKey.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(ivByte.getBytes()));
            byte[] encrypted = cipher.doFinal(originalContent.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * AES解密
     * 填充模式AES/CBC/PKCS7Padding
     * 解密模式128
     * @param content 目标密文
     * @return
     * @throws Exception
     */
    public static String decrypt(String content) {
        Security.addProvider(new BouncyCastleProvider());
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(encryptKey.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte.getBytes()));// 初始化
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
            return new String(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

//    public static void main(String[] args) {
//        String encryptStr = encrypt("{\"time\":\"1658891318223\"}");
//        String rawStr = decrypt(encryptStr);
//        System.out.println(encryptStr);
//        System.out.println(rawStr);
//    }
}